package com.cj.service.impl;

import com.cj.mapper.CommentMapper;
import com.cj.pojo.Comment;
import com.cj.pojo.CommentStatus;
import com.cj.pojo.PageBean;
import com.cj.service.CommentService;
import com.cj.utils.ThreadLocalUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Override
    public void add(Comment comment) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        comment.setUserId(userId.longValue());
        comment.setCreatedAt(LocalDateTime.now());
        comment.setUpdatedAt(LocalDateTime.now());
        comment.setStatus(CommentStatus.PUBLISHED);
        comment.setLikeCount(0);
        comment.setIsDeleted(0);
        commentMapper.add(comment);
    }

    @Override
    @Transactional
    public void batchDelete(List<Long> ids) {
        if (ids != null && !ids.isEmpty()) {
            commentMapper.batchDelete(ids);
        }
    }

    @Override
    public void update(Comment comment) {
        comment.setUpdatedAt(LocalDateTime.now());
        commentMapper.update(comment);
    }

    @Override
    public void delete(Long id) {
        commentMapper.delete(id);
    }

    @Override
    public PageBean<Comment> listByArticle(Long articleId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Comment> comments = commentMapper.findByArticleId(articleId, (pageNum - 1) * pageSize, pageSize);
        Page<Comment> p = (Page<Comment>) comments;
        return new PageBean<>(p.getTotal(), p.getResult());
    }

    @Override
    public PageBean<Comment> listByUser(Long userId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Comment> comments = commentMapper.findByUserId(userId, (pageNum - 1) * pageSize, pageSize);
        Page<Comment> p = (Page<Comment>) comments;
        return new PageBean<>(p.getTotal(), p.getResult());
    }

    @Override
    public void reply(Long parentId, Comment comment) {
        comment.setParentId(parentId);
        this.add(comment);
    }

    @Override
    public void like(Long id) {
        commentMapper.incrementLikeCount(id);
    }

    @Override
    public PageBean<Comment> listReplies(Long parentId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Comment> replies = commentMapper.findReplies(parentId, (pageNum - 1) * pageSize, pageSize);
        Page<Comment> p = (Page<Comment>) replies;
        return new PageBean<>(p.getTotal(), p.getResult());
    }
}
